package cdu.sl.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 登录检查过滤器
 * 拦截未登录用户访问系统
 */
public class LoginCheckFilter implements Filter {
    
    private static final Logger logger = LoggerFactory.getLogger(LoginCheckFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("LoginCheckFilter 初始化成功");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        
        // 获取请求URI
        String requestURI = request.getRequestURI();
        logger.debug("拦截到请求: {}", requestURI);
        
        // 不需要检查的路径
        String[] urls = new String[]{
                "/users/login",
                "/page/login",
                "/css/",
                "/js/",
                "/images/",
                "/favicon.ico"
        };
        
        // 检查请求是否需要放行
        boolean check = check(requestURI, urls);
        
        // 如果不需要处理，则直接放行
        if(check){
            logger.debug("请求 {} 无需登录验证，直接放行", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        
        // 获取Session中的用户信息
        HttpSession session = request.getSession();
        Object userInfo = session.getAttribute("userInfo");
        
        // 如果用户已登录，则放行
        if(userInfo != null){
            logger.debug("用户已登录，放行请求: {}", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        
        // 用户未登录，重定向到登录页面
        logger.info("用户未登录，拦截请求: {}, 重定向到登录页面", requestURI);
        response.sendRedirect(request.getContextPath() + "/page/login");
    }
    
    /**
     * 检查当前请求是否需要处理
     * @param requestURI
     * @param urls
     * @return
     */
    public boolean check(String requestURI, String[] urls){
        for (String url : urls) {
            if(requestURI.contains(url)){
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        logger.info("LoginCheckFilter 销毁");
    }
} 